package com.xwaf.platform.web.controller.pay;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.xwaf.platform.common.utils.JsonMapper;
import com.xwaf.platform.common.utils.http.HttpUtil;
import com.xwaf.platform.common.web.BaseController;
import com.xwaf.platform.system.api.entity.three.wx.WechatSmallRequest;
import com.xwaf.platform.system.api.entity.three.wx.WechatSmallResponse;
import com.xwaf.platform.system.api.entity.three.wx.WeiXinOAuthInfoQuery;
import com.xwaf.platform.system.api.entity.three.wx.WeiXinQrcodeOAuthInfo;
import com.xwaf.platform.system.api.service.pay.WeiXinService;
import com.xwaf.platform.web.util.GetSmallQrCode;
import com.xwaf.platform.web.util.OSSManageUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(tags = "微信小程序")
@RequestMapping(value = "/x/wxSmall/")
public class WeiXinSmallController extends BaseController {

	@Autowired
	private OSSManageUtil ossUtil;
	@Autowired
	private WeiXinService weiXinService;

	/**
	 * 
	 * <p>
	 * 小程序前台 bindGetUserInfo / getPhoneNumber 授权登录时调用
	 * <p>
	 * 
	 * @author 李聪 <br>
	 * @email xwaf_love@yeah.net <br>
	 * @since JDK 1.8<br>
	 * @date 2019年12月30日 上午9:30:24 <br>
	 * @see 无<br>
	 * @param userSmallRequest
	 * @return
	 * @throws Exception
	 * @demo <br>
	 */
	@ApiOperation(value = "小程序前台 bindGetUserInfo / getPhoneNumber 授权登录时调用", httpMethod = "POST")
	@PostMapping(value = "/smallWxAuth")
	public WechatSmallResponse smallWxAuth(@RequestBody WechatSmallRequest userSmallRequest) throws Exception {
		logger.info("----------smallWxAuth start--------");
		logger.info("smallWxAuth-request:" + userSmallRequest.toString());
		WechatSmallResponse userResponse = new WechatSmallResponse();
		checkNotNull(userSmallRequest, "请求信息无效");
		checkNotNull(userSmallRequest.getJs_code(), "Js_code不能为空");
		checkNotNull(userSmallRequest.getEncryptedData(), "encryptedData不能为空");
		checkNotNull(userSmallRequest.getIv(), "iv不能为空");
		// 获取session_key的方法
		org.json.JSONObject jsonObject = weiXinService.getOpenId(userSmallRequest.getJs_code());
		String openid = jsonObject.getString("openid");
		String session_key = jsonObject.getString("session_key");
		String unionid = "";
		if (jsonObject.has("unionid")) {
			unionid = jsonObject.getString("unionid");
		}
		logger.info("sessionkey===" + session_key + ",openid==" + openid + ",unionid=" + unionid);
		// 解密方法，然后返回给小程序就OK了
		JSONObject obj = weiXinService.getUserInfo(userSmallRequest.getEncryptedData(), session_key,
				userSmallRequest.getIv());
		logger.info("getUserInfo response:" + obj);
		userResponse.setOpenid(openid);
		userResponse.setUnionid(unionid);
		if ((userSmallRequest.getType()).equals("1")) {
			userResponse.setPhoneNumber(obj.getString("phoneNumber"));
		} else if ((userSmallRequest.getType()).equals("2")) {
			userResponse.setNickName((String) obj.get("nickName"));
		} else {
			checkNotNull(false, "type参数错误");
		}
		logger.info("----------smallWxAuth end--------");
		return userResponse;
	}

	@ApiOperation(value = "小程序小太阳二维码", httpMethod = "GET")
	@GetMapping(value = "/getSmallQrcode")
	@ResponseBody
	public String getWXQrcode(HttpServletRequest request, HttpServletResponse response) throws Exception {
		WeiXinOAuthInfoQuery oAuthInfoQuery = new WeiXinOAuthInfoQuery();
		// 获取公众号传过来的code
		String code = request.getParameter("code");
		logger.info("----------------开始进入getSmallQrcode-----------code=" + code);
		String url = "url错误";
		if (null != code && !"".equals(code)) {
			oAuthInfoQuery = getSmallOAuthInfoQrcode(code);
			String sceneStr = request.getParameter("scene");
			url = new GetSmallQrCode().getminiqrQr(ossUtil, URLEncoder.encode("OPENID", "UTF-8"),
					oAuthInfoQuery.getAccess_token());
		} else {
			logger.error("get code is fail!");
		}
		logger.info("----------------结束getSmallQrcode-----------");
		return url;
	}

	private WeiXinOAuthInfoQuery getSmallOAuthInfoQrcode(String code) throws IOException {
		String o_auth_openid_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
		// 替换参数(这里的值需要主动替换的)
		String requestUrl = o_auth_openid_url.replace("APPID", "SMALL_APPID").replace("SECRET", "SMALL_SECRET")
				.replace("JSCODE", code);
		System.out.println("微信请求参数==========" + requestUrl);
		String result = HttpUtil.doRequest(requestUrl, null, HttpUtil.GET);
		System.out.println("微信请求响应==========" + result);
		WeiXinQrcodeOAuthInfo oAuthInfo = (WeiXinQrcodeOAuthInfo) JsonMapper.jsonToObject(result,
				WeiXinQrcodeOAuthInfo.class);
		return new WeiXinOAuthInfoQuery(oAuthInfo);
	}
}
